package com.example.chat.service.impl;

import com.example.chat.entity.ChatSession;
import com.example.chat.entity.FileUpload;
import com.example.chat.mapper.ChatSessionMapper;
import com.example.chat.mapper.FileUploadMapper;
import com.example.chat.model.FileChatDO;
import com.example.chat.model.FileChatModel;
import com.example.chat.service.FileChatService;
import com.example.chat.service.VectorSearchService;
import com.example.common.common.config.filter.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.document.Document;
import org.springframework.stereotype.Service;
import com.example.common.utils.StringUtils;

import java.util.List;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/8/5 23:11
 **/
@Service
@RequiredArgsConstructor
public class FileChatServiceImpl implements FileChatService {
    private final static String USER_ID_FILTER = "@user_id:{%s}";
    private final static String SOURCE_FILTER = "@source:{%s}";
    private final static Integer MIN_TOP_K = 3;

    private final ChatSessionMapper chatSessionMapper;
    private final FileUploadMapper fileUploadMapper;
    private final VectorSearchService vectorSearchService;
    @Override
    public boolean createFileChat(FileChatModel fileChatModel) {
        // 查询chatId
        ChatSession existChatSession = chatSessionMapper.getChatSessionByChatId(fileChatModel.getChatId());
        if (existChatSession != null) {
            return true;
        }
        // todo 查询文件名称
        FileUpload existFileUpload = fileUploadMapper.queryFileUpload(null, fileChatModel.getFilename());
        if (existFileUpload == null) {
            throw new RuntimeException("文件上传异常");
        }

        // 创建文件对话记录
        ChatSession chatSession = ChatSession.builder()
                .chatId(fileChatModel.getChatId())
                .chatName(fileChatModel.getFilename())
                .userId(UserContext.getCurrentUser().getUserId())
                .type("file-chat")
                .build();
        chatSessionMapper.insertChatSession(chatSession);
        return true;
    }

    @Override
    public FileChatDO getFileChatInfo(String chatId) {
        return chatSessionMapper.getFileChatInfo(chatId);
    }

    @Override
    public String getSimilaritySearch(String chatId, String requestContent) {
        FileChatDO fileChatInfo = getFileChatInfo(chatId);

        String filter = String.format(
                "user_id == '%s' && source == '%s*'",
                StringUtils.replaceStr(UserContext.getCurrentUser().getUserId()),
                StringUtils.replaceStr(fileChatInfo.getFileId().split("\\.")[0])
        );
        List<Document> docs = vectorSearchService.similaritySearch(requestContent, filter, MIN_TOP_K);

        StringBuilder sb = new StringBuilder();
        sb.append("You are an assistant with access to a knowledge base.\n")
                .append("Use the following retrieved context to answer the user's question.\n\n")
                .append("## User Question:\n")
                .append(requestContent).append("\n\n")
                .append("## Retrieved Context:\n");

        for (int i = 0; i < docs.size(); i++) {
            Document doc = docs.get(i);
            sb.append("### Document ").append(i + 1).append("\n");

            // 内容（截断避免过长）
            String content = doc.getText();
            if (content.length() > 1000) {
                content = content.substring(0, 1000) + "...";
            }
            sb.append(content).append("\n");

            // 元数据
//            sb.append("Source: ").append(doc.getMetadata().get("vector_score")).append("\n\n");
        }

        sb.append("Answer the question based only on the retrieved context above.\n");

        return sb.toString();
    }
}
